package com.snow.framework.core.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author 李朋
 * @desc  通过反射调用类中方法，实现赋值或者取值
 * @date 2018-3-20
 */
public class MethodInvoke {

    /**
     * @desc  通过反射调用set方法赋值
     * @param object 实例化的对象
     * @param clazz 类的类型
     * @param filedName 属性
     * @param filedValue 属性值
     * @param typeClass 属性类型
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static void invokeSetMethod(Object object, Class<?> clazz
            , String filedName, Object filedValue
            , Class<?> typeClass) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method = MethodObtain.obtainSetMethod(clazz, filedName, String.class);
        method.invoke(object, filedValue);
    }

    /**
     * @desc 通过反射调用get方法获取值
     * @param object 实例化的对象
     * @param clazz 类的类型
     * @param filedName 属性
     * @return Object 获取的值
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static Object invokeGetMethod(Object object, Class<?> clazz, String filedName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method = MethodObtain.obtainGetMethod(clazz, filedName);
        return method.invoke(object);
    }

    /**
     * @desc 通过反射设置属性值（批量）
     * @param object 实例化的对象
     * @param map key-方法实例，value-属性值
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static void invokeSetValueBatch(Object object, Map<Method, Object> map) throws InvocationTargetException, IllegalAccessException {
        for (Map.Entry<Method, Object> entry : map.entrySet()){
            entry.getKey().invoke(object, entry.getValue());
        }
    }

    /**
     * @desc 通过反射设置属性值（单个）
     * @param object 实例化的对象
     * @param method 方法
     * @param filedValue 属性值
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static void invokeSetValue(Object object, Method method, Object filedValue) throws InvocationTargetException, IllegalAccessException {
        method.invoke(object, filedValue);
    }

}
